package com.smart.platform.utils;


import com.jcraft.jsch.*;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

/**
 * 上传文件工具类
 *
 * @author 王玉涛
 * @Param
 * @date 2017-10-24 21:32
 */
@Component
@ConfigurationProperties(prefix = "fileYml")
public class FileUtil implements Serializable {

    private String UPLOAD;//本地仓库路径
    private String showUrl;//服务器地址
    private String TOURL;//服务器路径
    private String USERNAME;
    private String PASS;
    private String URL;
    private int PORT;
    private String SERVERIP;
    private Double LNG;
    private Double LAT;

    public String getUPLOAD() {
        return UPLOAD;
    }

    public void setUPLOAD(String UPLOAD) {
        this.UPLOAD = UPLOAD;
    }

    public String getShowUrl() {
        return showUrl;
    }

    public void setShowUrl(String showUrl) {
        this.showUrl = showUrl;
    }

    public String getTOURL() {
        return TOURL;
    }

    public void setTOURL(String TOURL) {
        this.TOURL = TOURL;
    }

    public String getUSERNAME() {
        return USERNAME;
    }

    public void setUSERNAME(String USERNAME) {
        this.USERNAME = USERNAME;
    }

    public String getPASS() {
        return PASS;
    }

    public void setPASS(String PASS) {
        this.PASS = PASS;
    }

    public String getURL() {
        return URL;
    }

    public void setURL(String URL) {
        this.URL = URL;
    }

    public int getPORT() {
        return PORT;
    }

    public void setPORT(int PORT) {
        this.PORT = PORT;
    }

    public String getSERVERIP() {
        return SERVERIP;
    }

    public void setSERVERIP(String SERVERIP) {
        this.SERVERIP = SERVERIP;
    }

    public Double getLNG() {
        return LNG;
    }

    public void setLNG(Double LNG) {
        this.LNG = LNG;
    }

    public Double getLAT() {
        return LAT;
    }

    public void setLAT(Double LAT) {
        this.LAT = LAT;
    }

    /**
     * 孙吴资源地址配置
     * */
//    public static String UPLOAD = "D:\\smart_city_files\\";//本地仓库路径
//    public static String showUrl = "http://60.219.169.118:8099/cg/";//孙吴服务器地址
//    public static String TOURL = "/home/mydata/cg/";//服务器路径
//    public static String USERNAME = "root";
//    public static String PASS = "4kctMS";
//    public static String URL = "60.219.169.118";
//    public static int PORT = 2205;

    /**
     * 漠河资源地址配置
     * */
//    public static String UPLOAD = "D:\\smart_city_files\\";//本地仓库路径
//    public static String showUrl = "http://202.97.207.106:9091/cg/";//漠河服务器地址
//    public static String TOURL="/home/newspaces/cg/";//服务器路径
//    public static String USERNAME = "root";
//    public static String PASS = "H3sucC";
//    public static String URL = "202.97.207.106";
//    public static int PORT = 2206;

    /**
     * 开发资源地址配置
     * */
    //    public static String UPLOAD = "D:\\smart_city_files\\";//本地仓库路径
//    public static String showUrl = "http://10.64.42.119:8090/";//服务器地址
//    public static String TOURL="/var/digital_city_manage/";//服务器路径
//    public static String USERNAME = "root";
//    public static String PASS = "123!@#qwe";
//    public static String URL = "10.64.42.119";
//    public static int PORT = 22;
    public List filesUpload(MultipartFile[] files) {
        List fileNames = new ArrayList();
        //判断file数组不能为空并且长度大于0
            if (files[0].getOriginalFilename()!=null && !"".equals(files[0].getOriginalFilename())) {
            //循环获取file数组中得文件
                for (int j = 0; j < files.length; j++) {
                    MultipartFile file = files[j];
                    //保存文件
                    String fileName=saveFile(file);
                    fileNames.add(fileName);
                }
                System.out.println(fileNames);
                return fileNames;
            }
        // 重定向
        return null;
    }

    /***
     * 保存单个文件
     * @param file
     * @return
     */
    private String saveFile(MultipartFile file) {
        ChannelSftp sftp = null;
        Channel channel = null;
        Session sshSession = null;
        String name = fileNewName(file);
        InputStream is =null;
        // 判断文件是否为空
        if (!file.isEmpty()) {
            try {
                is = file.getInputStream();
                JSch jsch = new JSch();//创建JSch对象
                jsch.getSession(USERNAME,URL,PORT);// 根据用户名，主机ip，端口获取一个Session对象
                sshSession = jsch.getSession(USERNAME,URL,PORT);
                sshSession.setPassword(PASS);
                Properties sshConfig = new Properties();
                sshConfig.put("StrictHostKeyChecking", "no");
                sshSession.setConfig(sshConfig);// 为Session对象设置properties
                sshSession.setTimeout(60000); // 设置timeout时间
                sshSession.connect(60000);// 通过Session建立链接
                channel = sshSession.openChannel("sftp"); // 打开SFTP通道
                channel.connect(100000);// 建立SFTP通道的连接
                sftp = (ChannelSftp) channel;
                String dst = TOURL+name; // 服务器文件名
                sftp.put(is,dst);//上传服务器
                sftp.quit();
            }  catch (JSchException e) {
                e.printStackTrace();
            } catch (SftpException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                closeChannel(sftp);
                closeChannel(channel);
                closeSession(sshSession);
            }
        }
        return name;
    }
    private static void closeChannel(Channel channel) {
        if (channel != null) {
            if (channel.isConnected()) {
                channel.disconnect();
            }
        }
    }

    private static void closeSession(Session session) {
        if (session != null) {
            if (session.isConnected()) {
                session.disconnect();
            }
        }
    }

    public static String byte2hex(byte[] b) // 二进制转字符串
    {
        StringBuffer sb = new StringBuffer();
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1){
                sb.append("0" + stmp);
            }else{
                sb.append(stmp);
            }

        }
        return sb.toString();
    }

    public static byte[] hex2byte(String str) { // 字符串转二进制
        if (str == null)
            return null;
        str = str.trim();
        int len = str.length();
        if (len == 0 || len % 2 == 1)
            return null;
        byte[] b = new byte[len / 2];
        try {
            for (int i = 0; i < str.length(); i += 2) {
                b[i / 2] = (byte) Integer.decode("0X" + str.substring(i, i + 2)).intValue();
            }
            return b;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取系统时间
     *
     * @author yxd
     * @Param
     * @date 2017-12-4 9:32
     */
    public String NowDate(){
        Date date=new Date();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
        return sdf.format(date);
    }

    /**
     * 上传文件重命名
     *
     * @author yxd
     * @Param
     * @date 2017-12-4 9:32
     */

    public String fileNewName(MultipartFile file){
        String[] fileName=file.getOriginalFilename().toString().split("\\.");
        String fileNewName=System.currentTimeMillis()+"."+fileName[1];
        return fileNewName;
    }

    /**
     * 删除本地仓库文件
     *
     * @author yxd
     * @Param
     * @date 2017-12-4 9:32
     */
    public static boolean delete(String fileName) {
        File file = new File(fileName);
        if (!file.exists()) {
            System.out.println("删除文件失败:" + fileName + "不存在！");

        }
        return deleteFile(fileName);
    }

    public static boolean deleteFile(String fileName) {
        File file = new File(fileName);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                System.out.println("删除单个文件" + fileName + "成功！");
                return true;
            } else {
                System.out.println("删除单个文件" + fileName + "失败！");
                return false;
        }
        } else {
            System.out.println("删除单个文件失败：" + fileName + "不存在！");
            return false;
        }
    }

    /***
     * 上传文件 用@RequestParam注解来指定表单上的file为MultipartFile
     *
     * @param file
     * @return
     */
    public  String fileUpload(MultipartFile file) {
//        FTPClient ftpClient = new FTPClient();
//        FileInputStream fis = null;
//        // 判断文件是否为空
//        if (!file.isEmpty()) {
//            try {
//
//                ftpClient.connect("10.64.42.119");
//                ftpClient.login("root", "123!@#qwe");
//                File srcFile = new File(file.getOriginalFilename());
//                srcFile.setWritable(true,false);
//                fis = new FileInputStream(srcFile);
//                ftpClient.changeWorkingDirectory("/var");
//                ftpClient.setBufferSize(1024);
//                ftpClient.setControlEncoding("UTF-8");
//                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
//                ftpClient.storeFile(file.getOriginalFilename(), fis);
        // 判断文件是否为空
        if (!file.isEmpty()) {
            try {
                // 文件保存路径
                String path = UPLOAD + file.getOriginalFilename();
                String name = file.getOriginalFilename();
                //上传
                String fileName=saveFile(file);
//            String fileName = file.getOriginalFilename();
//			 request.setAttribute("fileName", fileName);
                return fileName;

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

}
